﻿using System;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using Conusic;
using ConusicUI.Properties;

namespace ConusicUI
{
    /// <summary>
    /// Description of AutoUpdate.
    /// </summary>
    public static class AutoUpdate
    {
        /// <summary>
        /// Check updates every day
        /// </summary>
        private const long updatePeriudCheckTicks = 3600L*24*1000*10000;

        private const string lastCheckTimeParamName = "autoupdateLastCheck";

        public static void CheckUpdateIfEnabled()
        {
            if (Settings.Default.AutoUpdate)
            {
                CheckUpdate();
            }
        }

        private static bool IsItTimeToCheckUpdate()
        {
            long deltaTime = DateTime.Now.Ticks - Settings.Default.lastCheckTimeParamName ;
            if (deltaTime > updatePeriudCheckTicks || deltaTime <= 0)
            {
                return true;
            }
            return false;
        }

        private static void CheckUpdate()
        {
            if (!IsItTimeToCheckUpdate()) return;

            Settings.Default.lastCheckTimeParamName = DateTime.Now.Ticks;
            string page = null;
            try
            {
                 page = SimpleHttp.RequestPage("http://s.3po.ru/conusic/update.ini");
            }
            catch (Exception)
            {
                return;
            }

            Match match;
            if (!(match = Regex.Match(page, "version=([.0-9]*)")).Success) return;
            Version avaliableVersion = new Version(match.Groups[1].ToString());
            Version applicationVersion = Assembly.GetEntryAssembly().GetName().Version;
            
            if (avaliableVersion > applicationVersion)
            {
                if (File.Exists("updateConusic.exe"))
                {
                    System.Diagnostics.Process.Start("updateConusic.exe");
                    Environment.Exit(0);
                }
                else
                {
                    ErrorReport.Show(
                        new FileNotFoundException(
                            "Автообновление не найдено, перезагрузите программу с сайта http://3po.ru"), null);
                }
            }
        }
    }
}